<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="130px"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否启用报警规则" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择是否启用报警规则"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.VMIOT_TASK_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="被监测设备" prop="monitorDeviceId">
        <el-select
          v-model="queryParams.monitorDeviceId"
          clearable
          class="!w-240px"
          placeholder="请选择被监测设备"
        >
          <el-option
            v-for="item in monitorDeviceList"
            :key="item.id"
            :label="item.deviceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vmiot:task:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="operate-bar">
      <el-button
        type="primary"
        plain
        @click="openForm('create')"
        v-hasPermi="['vmiot:task:create']"
      >
        <Icon icon="ep:plus" class="mr-5px" /> 新增
      </el-button>
    </div>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="描述" align="center" prop="remark" />
      <el-table-column label="运行状态" align="center" prop="runningState">
        <template #default="scope">
          <el-text class="mx-1" v-if="scope.row.runningState === 1" type="success">运行中</el-text>
          <el-text class="mx-1" v-if="scope.row.runningState === 0" type="danger">未运行</el-text>
        </template>
      </el-table-column>
      <el-table-column label="是否启用报警规则" align="center" prop="state">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.VMIOT_TASK_STATE" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="被监测设备" align="center" prop="monitorDeviceName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="editTask(scope.row.id)"
            v-hasPermi="['vmiot:task:update']"
          >
            配置任务
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['vmiot:task:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['vmiot:task:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TaskForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import TaskForm from './TaskForm.vue'
import { TaskApi, TaskVO } from '@/api/vmiot/task'
import { MonitorDeviceApi } from '@/api/vmiot/monitordevice'
import { AlgengineApi } from '@/api/vmiot/algengine'

/** 任务 列表 */
defineOptions({ name: 'Task' })

const { push } = useRouter()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const monitorDeviceList = ref<any[]>([])
const loading = ref(true) // 列表的加载中
const list = ref<TaskVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  state: undefined,
  monitorDeviceId: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const editTask = (id: number) => {
  push('/task/edit?id=' + id)
}

/** 删除按钮操作 */
const handleDelete = async (rowData: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm()

    // 发起删除
    await deleteTaskAndSauInstance(rowData)
    //
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/**
 * 删除任务数据，删除前先删除sau实例
 * @param rowData
 */
const deleteTaskAndSauInstance = async (rowData) => {
  const content = rowData.content ? JSON.parse(rowData.content) : {}

  const nodes = Array.isArray(content.nodes) ? content.nodes : []

  const promises = nodes
    .filter((node) => node.type === 'default' && node.data?.sauInstanceId)
    .map(async (node) => {
      try {
        await AlgengineApi.deleteSau(node.data.sauInstanceId)
      } catch (error) {
        console.log('删除 SAU 实例失败：', error)
      }
    })

  try {
    await Promise.all(promises)
  } catch (error) {
    console.log('批量删除 SAU 实例异常：', error)
  } finally {
    await TaskApi.deleteTask(rowData.id)
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskApi.exportTask(queryParams)
    download.excel(data, '任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const getMonitorDeviceList = async () => {
  try {
    const deviceList = await MonitorDeviceApi.getAllMonitorDeviceList()
    monitorDeviceList.value = deviceList
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getMonitorDeviceList()
  getList()
})
</script>
